package com.cel.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cel.Service.WxService;

/**
 * Servlet implementation class WxServlet
 */
@WebServlet("/wx")
//87bdfe817ed53a76
public class WxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
//				验证消息的确来自微信服务器
//           	signature 	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
//				timestamp 	时间戳
//				nonce 	    随机数
//				echostr 	随机字符串

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		// 校验签名
		if (WxService.check(timestamp, nonce, signature)) {
			PrintWriter out = response.getWriter();
			// 返回echostr参数
			out.print(echostr);
			out.flush();
			out.close();
			System.out.println("接入成功!");
		} else {
			System.out.println("接入失败!");
		}
	}

	// 接收消息和事件推送
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 处理消息事件推送
		Map<String, String> requestMap = WxService.parseRequest(request.getInputStream());
		System.out.println(requestMap);
		// 准备回复的数据包
		String respXml = WxService.getRespose(requestMap);
		System.out.println(respXml);
		PrintWriter out = response.getWriter();
		out.print(respXml);
		out.flush();
		out.close();
//		ServletInputStream is = request.getInputStream();
//		byte[] b = new byte[1024];
//		int len;
//		StringBuilder  sb =new StringBuilder();
//		while ((len=is.read(b))!=-1) {
//				sb.append(new String(b,0,len));
//			
//		}
//		System.out.println(sb.toString());

	}

}
